package com.gogowan.agroenterprise.widget;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.contorl.FtpUpload;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.model.PicturesInfo;
import com.gogowan.agroenterprise.utils.Utils;

/**
 * 图片专题的插入图片
 * 
 */
public class PicturesGridView extends ControlView {

	private Context context;
	private GridView gridView;
	private PicturesAdapter adapter;
	private SharedPreferences sharedPreferences;
	private String uploadfile;
	private String newCapturePhotoPath;
	private String dataStr;
	private String name;// 原图
	private String sname;// 缩略
	private String scaledName; // 压缩图
	private int uploadNum; // 上传几个图片标识
	private int system; // 农产品系统和供求系统的分类标识（1为农产品，2为供求系统）
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				PicturesInfo picturesInfo = (PicturesInfo) msg.obj;
				adapter.addPicturesInfo(picturesInfo);

				break;
			default:
				break;
			}
		}

	};

	public PicturesGridView(Context context, String data) {
		super(context, data);
		this.context = context;
		initControl();
		initData();
	}

	public PicturesGridView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		this.setOrientation(LinearLayout.VERTICAL);
		initControl();
		initData();
	}

	@Override
	public void setData(String newData) {
		super.setData(newData);
	}

	public List<PicturesInfo> getList() {
		return adapter.getDataList();
	}

	public void setList(List<PicturesInfo> list) {
		adapter.setList(list);
	}

	@Override
	public String getData() {
		return null;// IconUtils.imgToStr(bitmap);
	}

	public void clear() {
		adapter.clear();
	}

	public void initData() {
		sharedPreferences = context.getSharedPreferences("LoginINfo", 0);
		String string = sharedPreferences.getString("saveLoginInfo", "");
		LoginResultInfo loginResultInfo = (LoginResultInfo) Utils.fromJSON(
				string, LoginResultInfo.class);
		if (system == 1) {
			uploadfile = loginResultInfo.getFtpfile();
		} else if (system == 2) {
			uploadfile = loginResultInfo.getYxftpfile();
		}
		uploadfile = loginResultInfo.getFtpfile();
	}

	/**
	 * 初始化控件
	 * 
	 */
	public void initControl() {

		final LayoutInflater inflater = LayoutInflater.from(context);
		LinearLayout layout = (LinearLayout) inflater.inflate(
				R.layout.pictures_grid_view, null);
		this.addView(layout);

		gridView = (GridView) layout.findViewById(R.id.pictures_gride_gv);
		gridView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT));
		adapter = new PicturesAdapter(context, null, gridView);
		gridView.setAdapter(adapter);

		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) {
				if ((adapter.getCount() - 1) == position) {
					AlertDialog.Builder builder = new AlertDialog.Builder(
							context);
					builder.setTitle("选择方式");
					builder.setItems(new String[] { "拍摄照片", "本地照片(请选择jpg文件)" },
							new AlertDialog.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									if (which == 0) {
										Intent intent = new Intent(
												MediaStore.ACTION_IMAGE_CAPTURE);
										image2SDcard(intent);
										((Activity) context)
												.startActivityForResult(intent,
														0);
									} else if (which == 1) {
										Intent intent = new Intent(
												Intent.ACTION_GET_CONTENT);
										intent.setType("image/*");
										((Activity) context)
												.startActivityForResult(intent,
														1);
									}
								}
							});
					builder.show();
				} else {
					AlertDialog.Builder builder = new AlertDialog.Builder(
							context);
					builder.setTitle("选择方式");
					builder.setItems(new String[] { "编辑图片描述", "删除" },
							new AlertDialog.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									if (which == 0) {
										LayoutInflater inflater = LayoutInflater
												.from(context);
										View view = inflater.inflate(
												R.layout.image_dialog, null);
										final EditText text = (EditText) view
												.findViewById(R.id.image_dialog_et_message);
										new AlertDialog.Builder(context) {
										}.setView(view)
												// .setCancelable(false)
												.setPositiveButton(
														"确定",
														new AlertDialog.OnClickListener() {
															@Override
															public void onClick(
																	DialogInterface dialog,
																	int which) {

																adapter.editDiscription(
																		text.getText()
																				.toString(),
																		position);
															}
														}).show();

									} else if (which == 1) {
										boolean isDel = adapter.del(position);
										if (isDel) {
											Toast.makeText(context, "删除图片成功！",
													Toast.LENGTH_SHORT).show();
										} else {
											Toast.makeText(context, "删除图片失败！",
													Toast.LENGTH_SHORT).show();
										}
									}
								}
							});
					builder.show();
				}
			}
		});
	}

	public void image2SDcard(Intent intent) {
		File sdDir;
		String sdStatus = Environment.getExternalStorageState();
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
			Toast.makeText(context, "无SD卡", Toast.LENGTH_SHORT).show();
			return;
		} else {
			sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
		}

		Date date = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		File file = new File(sdDir.getPath() + "/AgricultureSystem/Image/");
		file.mkdirs();// 创建文件夹
		dataStr = formatter.format(date);
		newCapturePhotoPath = null;

		newCapturePhotoPath = sdDir.getPath() + "/AgricultureSystem/Image/"
				+ dataStr + ".jpg";

		name = newCapturePhotoPath;

		Uri uri = Uri.fromFile(new File(newCapturePhotoPath));
		intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
	}

	/**
	 * 
	 * @param requestCode
	 * @param resultCode
	 * @param data
	 * @param uploadNum
	 *            上传几张图片
	 * @param system
	 *            农产品系统和供求系统的分类标识（1为农产品，2为供求系统）
	 */
	public void onViewResult(int requestCode, int resultCode, Intent data,
			int uploadNum, int system) {
		this.uploadNum = uploadNum;
		this.system = system;
		try {
			if (resultCode == Activity.RESULT_OK) {
				if (requestCode == 0) {// 拍照
					// 填写描述,并上传
					showUploadDialog(newCapturePhotoPath, system);
				} else if (requestCode == 1) {
					Uri originalUri = data.getData(); // 获得图片的uri
					String[] proj = { MediaStore.Images.Media.DATA,
							MediaStore.Images.Media.SIZE };
					ContentResolver resolver = ((Activity) context)
							.getContentResolver();
					Cursor cursor = resolver.query(originalUri, proj, null,
							null, null);
					// 将光标移至开头 ，这个很重要，不小心很容易引起越界
					cursor.moveToFirst();
					final String fileName = cursor
							.getString(cursor
									.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
					// 填写描述,并上传
					name = fileName;
					showUploadDialog(fileName, system);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(context, "获取图片信息失败", Toast.LENGTH_SHORT).show();
		}
	}

	public void showUploadDialog(final String fileName, final int system) {
		LayoutInflater inflater = LayoutInflater.from(context);
		View view = inflater.inflate(R.layout.image_dialog, null);
		final EditText text = (EditText) view
				.findViewById(R.id.image_dialog_et_message);
		new AlertDialog.Builder(context) {
		}.setView(view)
		// .setCancelable(false)
				.setPositiveButton("上传", new AlertDialog.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						String message = text.getText().toString();
						try {

							FtpUpload ftpUpload = new FtpUpload(context,
									uploadfile, system);

							UploadImageAsync uploadImageAsync = new UploadImageAsync(
									ftpUpload, message);
							uploadImageAsync.execute(fileName);

						} catch (Exception e) {
							Toast.makeText(context, "上传图片失败",
									Toast.LENGTH_SHORT).show();
							e.printStackTrace();
						}
					}
				}).show();
	}

	/**
	 * 保存图片到sd卡
	 * 
	 * @param bitName
	 * @param mBitmap
	 */
	public void saveMyBitmap(String bitName, Bitmap mBitmap) {
		File f = new File("/sdcard/" + bitName + ".png");
		try {
			f.createNewFile();
		} catch (IOException e) {

		}
		FileOutputStream fOut = null;
		try {
			fOut = new FileOutputStream(f);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
		try {
			fOut.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			fOut.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public class UploadImageAsync extends MyAsyncTask {
		private FtpUpload ftpUpload;
		private String description;

		public UploadImageAsync(FtpUpload ftpUpload, String description) {
			this.ftpUpload = ftpUpload;
			this.description = description;
		}

		@Override
		protected Object doInBackground(Object... params) {
			String path = (String) params[0];
			FileOutputStream b = null;
			FileOutputStream zmStream = null;
			Bitmap bitmap = null;
			try {
				File sdDir;
				String sdStatus = Environment.getExternalStorageState();
				if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
					Toast.makeText(context, "没有发现SD卡", Toast.LENGTH_SHORT)
							.show();
					return null;
				} else {
					sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
				}

				SimpleDateFormat dateFormat = new SimpleDateFormat(
						"yyyyMMddHHmmssSSS");
				String dateStr = dateFormat.format(new Date());

				// 如果第一次上传图片是选择的从内存卡选择文件上传，创建以下两个图片的时候会出现FileNotFoundException
				// 原因：(1)没有创建文件夹，在没有文件夹情况下，创建文件将报错.解决方案为先创建文件夹。
				// (2)有文件夹，但文件所在位置无文件夹，即文件路径太深，超过二级。
				String dir = sdDir.getPath() + "/AgricultureSystem/Image";
				File directory = new File(dir);
				if (!directory.exists()) {
					directory.mkdirs();
				}

				// 500*500的图
				bitmap = Utils.zoom(path, 320);
				scaledName = "zm" + dateStr + ".jpg";
				String zmfileName = sdDir.getPath()
						+ "/AgricultureSystem/Image/" + scaledName;
				zmStream = new FileOutputStream(zmfileName);
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, zmStream);// 把数据写入文件
				bitmap.recycle();
				bitmap = null;
				// 小图
				bitmap = Utils.decodeFile(new File(zmfileName), 70);
				sname = "s" + dateStr + ".jpg";
				String sfileName = sdDir.getPath()
						+ "/AgricultureSystem/Image/" + sname;
				b = new FileOutputStream(sfileName);
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
				bitmap.recycle();
				bitmap = null;
				
				if (uploadNum == 1) {
					ftpUpload.ftpUpload(zmfileName);
				} else if (uploadNum == 2) {
					ftpUpload.ftpUpload(zmfileName);
					ftpUpload.ftpUpload(sfileName);
				}

				if (new File(path).exists()) {
					new File(path).delete();
				}

				return "1";

			} catch (Exception e) {
				Toast.makeText(context, "上传图片失败", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			} catch (OutOfMemoryError e) {
				Toast.makeText(context, "内存空间不足！", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			} catch (Throwable e) {
				Toast.makeText(context, "上传图片失败", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			} finally {
				try {
					if (bitmap != null && !bitmap.isRecycled()) {
						// 图片回收
						bitmap.recycle();
						bitmap = null;
					}
					if (b != null) {
						b.flush();
						b.close();
					}
					if (zmStream != null) {
						zmStream.flush();
						zmStream.close();
					}
				} catch (IOException e) {
					Toast.makeText(context, "outputStream close error",
							Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				} catch (OutOfMemoryError e) {
					Toast.makeText(context, "内存空间不足！",Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				} catch (Throwable e) {
					Toast.makeText(context, "未知异常",Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				}
			}
			return null;
		}// 返回json串作为onPostExecute(Object res)的参数 }

		@Override
		protected void onPostExecute(Object res) {
			try {

				if (!ftpUpload.close()) {
					Toast.makeText(context, "上传失败", Toast.LENGTH_SHORT).show();
					return;
				} else {

					if (!Utils.isEmpty(String.valueOf(res))) // 上传成功
					{
						PicturesInfo picturesInfo = new PicturesInfo();

						picturesInfo.setUrl(name);
						picturesInfo.setSurl(sname);
						picturesInfo.setPureName(scaledName);
						picturesInfo.setDescription(description);

						android.os.Message msg = new android.os.Message();
						msg.what = 0;
						msg.obj = picturesInfo;
						handler.sendMessage(msg);
					} else { // 未知错误
						Toast.makeText(context, "上传失败", Toast.LENGTH_SHORT)
								.show();
					}
				}

			} catch (Exception e) {
				Toast.makeText(context, "上传失败", Toast.LENGTH_SHORT).show();
			}
			super.onPostExecute(res);
		}
	}

	public void setEnabled(boolean isEnabled) {
		gridView.setEnabled(isEnabled);
	}

	public void setNewCapturePhotoPath(String newCapturePhotoPath) {
		this.newCapturePhotoPath = newCapturePhotoPath;
	}

	public void setName(String name) {
		this.name = name;
	}
}